<template>
  <div>
    <div v-show="showTable" class="p-6 space-y-4">
      <!-- 顶部装置/单元选择 + 检索栏 -->
      <el-card shadow="never" class="rounded-lg">
        <div class="flex flex-col gap-4">
          <el-form :model="filters" label-position="top" class="search-form" @keyup.enter="handleQuery">
            <el-row :gutter="12" align="bottom">
              <el-col :span="5">
                <el-form-item label="顶上事件">
                  <el-input v-model="filters.topEvent" placeholder="请输入" clearable/>
                </el-form-item>
              </el-col>
              <el-col :span="5">
                <el-form-item label="设备名称/位号">
                  <el-input v-model="filters.hazardSourceEqNum" placeholder="请输入" clearable/>
                </el-form-item>
              </el-col>
              <el-col :span="5">
                <el-form-item label="装置名称">
                  <el-input v-model="filters.device" placeholder="请输入" clearable/>
                </el-form-item>
              </el-col>
              <el-col :span="5">
                <el-form-item label="屏障名称">
                  <el-input v-model="filters.barrier" placeholder="请输入" clearable/>
                </el-form-item>
              </el-col>
              <el-col :span="3" class="flex justify-end items-end gap-2">
                <el-button type="primary" :loading="queryLoading" @click="handleQuery">
                  <el-icon class="mr-1">
                    <Search/>
                  </el-icon>
                  查询
                </el-button>
              </el-col>
            </el-row>
          </el-form>
          <div>
            <el-button type="primary" @click="onAdd">
              <svg-icon icon-class="add" class="mr-2"></svg-icon>
              新增
            </el-button>
            <el-button type="danger" plain :disabled="single" @click="onDelete()">
              <svg-icon icon-class="delete" class="mr-2"></svg-icon>
              删除
            </el-button>
            <el-button type="primary" @click="handleQuery">
              <svg-icon icon-class="batch-import" class="mr-2"></svg-icon>
              批量导入
            </el-button>
            <el-button type="danger" plain :disabled="multiple" @click="onBatchDelete">
              <svg-icon icon-class="batch-delete" class="mr-2"></svg-icon>
              批量删除
            </el-button>
          </div>
        </div>
      </el-card>

      <!-- 数据表格 -->
      <el-card shadow="never" class="rounded-lg">
        <el-table v-loading="tableLoading" :data="tableData" @selection-change="handleSelectionChange">
          <el-table-column type="selection" width="55"/>
          <el-table-column label="序号" type="index" width="80" align="center" :index="indexMethod"/>
          <el-table-column prop="riskType" label="风险场景分类" min-width="120" align="center" show-overflow-tooltip/>
          <el-table-column prop="riskCode" label="风险清单编号" min-width="120" show-overflow-tooltip/>
          <el-table-column prop="device" label="所属装置" min-width="120" align="center" show-overflow-tooltip/>
          <el-table-column prop="unit" label="所属单元" min-width="120" align="center" show-overflow-tooltip/>
          <el-table-column prop="personLiable" label="责任人" min-width="120" align="center" show-overflow-tooltip/>
          <el-table-column prop="hazardSource" label="危险源" min-width="120" align="center" show-overflow-tooltip/>
          <el-table-column prop="hazardSourceEqNum" label="危险源设备位号" min-width="120" align="center"
                           show-overflow-tooltip/>
          <el-table-column prop="topEvent" label="顶上事件" min-width="120" align="center" show-overflow-tooltip/>
          <el-table-column prop="causesAndConsequences" label="原因后果" min-width="120" align="center"
                           show-overflow-tooltip/>
          <el-table-column prop="initialRisk" label="初始风险" min-width="120" align="center" show-overflow-tooltip/>
          <el-table-column prop="barrier" label="屏障" min-width="120" align="center" show-overflow-tooltip/>
          <el-table-column prop="residualRisk" label="残余风险" min-width="120" align="center" show-overflow-tooltip/>
          <el-table-column fixed="right" label="操作" width="160" align="center">
            <template #default="{ row }">
              <el-button link type="primary" @click="onView(row)">
                <svg-icon icon-class="view-details"></svg-icon>
                详情
              </el-button>
              <el-button link type="danger" @click="onDelete(row)">
                <svg-icon icon-class="delete"></svg-icon>
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>

        <div class="flex justify-end mt-4">
          <el-pagination
            v-model:current-page="pagination.currentPage"
            v-model:page-size="pagination.pageSize"
            :total="pagination.total"
            :page-sizes="[10, 20, 50]"
            layout="total, sizes, prev, pager, next, jumper"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
      </el-card>
    </div>
    <basic-info-form ref="basicInfoFormRef" @return-table="returnTable"/>
  </div>
</template>

<script setup lang="ts">
import {onMounted, reactive, ref} from 'vue';
import {ElMessage, ElMessageBox} from 'element-plus';
import {Search} from '@element-plus/icons-vue';
import BasicInfoForm from './basicInfoForm.vue';

interface BarrierRow {
  id: number;
  riskType: string;
  riskCode: string;
  device: string;
  unit: string;
  personLiable: string;
  hazardSource: string;
  hazardSourceEqNum: string;
  topEvent: string;
  causesAndConsequences: string;
  initialRisk: string;
  barrier: string;
  residualRisk: string;
}

// 显示表格
const showTable = ref(true);

// 表单
const basicInfoFormRef = ref(null);

// 搜索条件
const filters = reactive({
  topEvent: '',
  hazardSourceEqNum: '',
  device: '',
  barrier: ''
});

// 表格
const tableLoading = ref(false);
const queryLoading = ref(false);
const tableData = ref<BarrierRow[]>([]);

// 分页
const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0
});

// 模拟数据
const allRecords = ref<BarrierRow[]>([
  {
    id: 101,
    riskType: '风险场景分类',
    riskCode: '风险清单编号',
    device: '所属装置',
    unit: '所属单元',
    personLiable: '责任人',
    hazardSource: '危险源',
    hazardSourceEqNum: '危险源设备位号',
    topEvent: '顶上事件',
    causesAndConsequences: '原因后果',
    initialRisk: '初始风险',
    barrier: '屏障',
    residualRisk: '残余风险'
  },
  {
    id: 102,
    riskType: '风险场景分类1',
    riskCode: '风险清单编号1',
    device: '所属装置1',
    unit: '所属单元1',
    personLiable: '责任人1',
    hazardSource: '危险源1',
    hazardSourceEqNum: '危险源设备位号1',
    topEvent: '顶上事件1',
    causesAndConsequences: '原因后果1',
    initialRisk: '初始风险1',
    barrier: '屏障1',
    residualRisk: '残余风1险'
  }
]);

const indexMethod = (index: number) => (pagination.currentPage - 1) * pagination.pageSize + index + 1;
const ids = ref<Array<string | number>>([]);
const single = ref(true);
const multiple = ref(true);
const handleSelectionChange = (selection: BarrierRow[]) => {
  ids.value = selection.map((item) => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
};

const getFilteredRecords = () => {
  return allRecords.value.filter((r) => {
    const m1 = filters.topEvent ? r.topEvent.includes(filters.topEvent) : true;
    const m2 = filters.hazardSourceEqNum ? r.hazardSourceEqNum.includes(filters.hazardSourceEqNum) : true;
    const m3 = filters.device ? r.device === filters.device : true;
    const m4 = filters.barrier ? r.barrier === filters.barrier : true;
    return m1 && m2 && m3 && m4;
  });
};

const refreshTable = (records: BarrierRow[]) => {
  pagination.total = records.length;
  const start = (pagination.currentPage - 1) * pagination.pageSize;
  tableData.value = records.slice(start, start + pagination.pageSize);
};

const handleQuery = () => {
  queryLoading.value = true;
  tableLoading.value = true;
  setTimeout(() => {
    refreshTable(getFilteredRecords());
    queryLoading.value = false;
    tableLoading.value = false;
  }, 200);
};

const handleSizeChange = (size: number) => {
  pagination.pageSize = size;
  pagination.currentPage = 1;
  handleQuery();
};
const handleCurrentChange = (page: number) => {
  pagination.currentPage = page;
  handleQuery();
};

// 详情弹窗

const onDelete = (row?: BarrierRow) => {
  let id = null;
  if (row) {
    id = row.id;
  } else {
    id = ids.value[0];
  }
  if (!id) return;
  ElMessageBox.confirm('确认删除该记录？', '提示', {type: 'warning'}).then(() => {
    allRecords.value = allRecords.value.filter((r) => r.id !== id);
    handleQuery();
    ElMessage.success('删除成功');
  });
};
const onBatchDelete = () => {
  ElMessageBox.confirm('确认删除该记录？', '提示', {type: 'warning'}).then(() => {
    allRecords.value = allRecords.value.filter((r) => !ids.value.includes(r.id));
    handleQuery();
    ElMessage.success('删除成功');
  });
};

const onAdd = () => {
  showTable.value = false;
  basicInfoFormRef.value?.openForm('ADD');
};
const onView = (id: number) => {
  showTable.value = false;
  basicInfoFormRef.value?.openForm('VIEW', id);
};

const returnTable = () => {
  showTable.value = true;
  handleQuery();
};

onMounted(() => handleQuery());
</script>

<style scoped>
/* 无需自定义样式，保留作用域块避免污染 */
</style>
